const Controller = require('egg').Controller;


class order extends Controller {

    /**
     * 菜单跳转
     * @returns {Promise<void>}
     */
    async to(){
        const {app,ctx,service} = this;
        await ctx.render('/admin/order_query.ejs',{});
    }

    /**
     * 跳转编辑页面
     * @returns {Promise<void>}
     */
    // async toedit(){
    //     const {app,ctx,service} = this;
    //     //编辑id
    //     let id = ctx.request.query.id;
    //     await ctx.render('/admin/order_edit.ejs',{id:id});
    // }

    /**
     * 跳转详情页面
     * @returns {Promise<void>}
     */
    async todetail(){
        const {app,ctx,service} = this;
        //编辑id
        let id = ctx.request.query.id;
        await ctx.render('/admin/order_detail.ejs',{id:id});
    }

    /**
     * 查询接口
     * isPage 是否分页
     * limit offset 每页限制数 偏移量
     * search 搜索项
     * /admin/接口
     * type get
     * @returns {Promise<void>}
     */
    async index(){
        const {app,ctx,service} = this;
        //取get请求参数
        let param = ctx.query;
        //初始化变量 用于请求参数中缺失部分参数时不至于导致报错
        let limit = 10;
        let offset = 0;
        let search = '%%';
        let isPage = 'true';

        //循环请求参数 赋值 到变量
        app.lodash.forEach(param,(v,k)=>{
            switch (k) {
                case 'pageSize':
                    limit = parseInt(v);break;
                case 'limit':
                    limit = parseInt(v);break;
                case 'page':
                    offset = parseInt((v - 1) * limit);break;
                case 'number':
                    search = v;break;
                case 'isPage':
                   isPage = v;break;
            }
        });

        let where_sql = ``;
        if(!app.lodash.isEmpty(search)){
            where_sql = ` and a.number like '%${search}%' `;
        }
        let sql = `
            select a.number,a.id,b.realname,b.province,b.address,b.phone,c.username,a.is_complaint,a.status
            from fd_order a
            left join fd_address b on a.address_id = b.id
            left join fd_user c on c.id = a.user_id
            where a.deleted = '0' ${where_sql}
            limit ${offset},${limit}
        `;
        let count_sql = `
            select count(*) as total
            from fd_order a
            where a.deleted = '0' ${where_sql}
        `;

        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let data = await ctx.model.query(sql,sequelize_query_param);
        let count = await ctx.model.query(count_sql,sequelize_query_param);

        //返回
        ctx.body = {
            code : 0,
            data,
            count:count[0].total,
            msg : ''
        }
    }

    /**
     * 单个记录查询接口
     * /admin/接口/:id
     * type : get
     * @returns {Promise<void>}
     */
    async show(){
        const {app,ctx,service} = this;
        var moment = require('moment');
        //获取url请求参数
        let param = ctx.params;

        //创建规则
        const rule = {
            id:'required'
        };
        //验证
        const err = await app.validator.validate(param,rule);
        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误信息
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        let sql  = `
        select
        a.id,a.number,c.realname,c.province,c.address,c.phone,a.status,a.created_at,a.is_complaint,a.complaint,a.complaint_pic,a.replay,a.replay_pic,a.rete,a.evaluation,a.evaluation_pic,e.realname as staffname,f.name as storename
        from fd_order a
        left join fd_address c on c.id = a.address_id
        left join fd_user e on e.id = a.staff_id
        left join fd_store f on f.id = a.store_id
        where a.id = '${param.id}'
        `;
        const sequelize_query_param = {raw:true,type:app.Sequelize.QueryTypes.SELECT};
        let order = await ctx.model.query(sql,sequelize_query_param);
        order = order[0];

        sql = `
        select *
        from fd_order_list a
        left join fd_type b on b.id = a.type_id
        where a.deleted = '0' and a.order_id = '${param.id}'
        `;
        let orderList = await ctx.model.query(sql,sequelize_query_param);

        order.list = orderList;

        order.complaint_pic = order.complaint_pic == null ? []:order.complaint_pic.split(',');
        order.replay_pic = order.replay_pic == null ? []:order.replay_pic.split(',');
        order.evaluation_pic = order.evaluation_pic == null ? []:order.evaluation_pic.split(',');

        //返回
        ctx.body = {
            code : 200,
            data : order,
            msg : ''
        }
    }

    /**
     * 删除接口
     * /admin/接口/:id
     * type delete
     * @returns {Promise<void>}
     */
    async destroy(){
        const {app,ctx,service} = this;
        //获取url参数
        let param = ctx.params;

        //创建规则
        const rule = {
            id:'required'
        };
        //验证
        const err = await app.validator.validate(param,rule);
        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        //开启事务
        let t = await ctx.model.transaction();
        try {
            let order = await ctx.model.findOne({where:{id},transaction:t,lock:t.LOCK.UPDATE});
            order.status = '13';
            await order.save({transaction:t});
            //提交事务
            t.commit();
        }catch (e) {
            //失败回滚
            t.rollback();
            //抛出错误信息
            ctx.throw(500,e.message)
        }
        //返回
        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }


    /**
     * 更新接口
     * /admin/接口/:id
     * type put
     * @returns {Promise<void>}
     */
    // async update(){
    //     const {app,ctx,service} = this;
    //     //获取post请求参数
    //     let param = ctx.request.body.data;
    //     //获取url请求参数
    //     param.id = ctx.params.id;
    //
    //     //创建规则
    //     const rule = {
    //         id:'required',
    //         name:'required',
    //         code:'required|alpha',//仅支持字母
    //         path:'required',//仅支持字母
    //     };
    //     //验证
    //     const err = await app.validator.validate(param,rule);
    //     //判断验证结果
    //     if(!app.lodash.isEmpty(err)){
    //         //抛出验证错误信息
    //         ctx.throw(401,err[0].field+' -- '+err[0].message);
    //     }
    //
    //     //调用service获取结果
    //     let rs = await service.orderService.update(param);
    //
    //     //判断处理结果
    //     if(!rs){
    //         //抛出处理失败错误信息
    //         ctx.throw(501,'记录查询失败');
    //     }
    //
    //     //返回
    //     ctx.body = {
    //         code : 200,
    //         data : rs,
    //         msg : ''
    //     }
    // }
}

module.exports = order;
